//订阅者回调签名
typedef void EventCallback(arg);

class EventMgr {
  //私有构造函数
  EventMgr._();

  //保存事件订阅者队列，key:事件名(id)，value: 对应事件的订阅者队列
  static final _eventMap = <Object, List<EventCallback>?>{};

  //添加订阅者
  static void on(EventType eventType, EventCallback f) {
    _eventMap[eventType] ??= <EventCallback>[];
    _eventMap[eventType]!.add(f);
  }

  //移除订阅者
  static void off(EventType eventType, [EventCallback? f]) {
    var list = _eventMap[eventType];
    if (list == null) return;
    if (f == null) {
      _eventMap[eventType] = null;
    } else {
      list.remove(f);
    }
  }

  //触发事件，事件触发后该事件所有订阅者会被调用
  static void send(EventType eventType, [data]) {
    print('/触发事件，事件触发后该事件所有订阅者会被调用');
    var list = _eventMap[eventType];
    if (list == null) return;
    int len = list.length - 1;
    //反向遍历，防止订阅者在回调中移除自身带来的下标错位
    for (var i = len; i > -1; --i) {
      list[i](data);
    }
  }
}

enum EventType {
  ///选择地址
  selectAddress,

  ///刷新地址列表
  refreshAddress,

  ///刷新购物车
  refreshCar,

  ///刷新登录状态
  refreshLogin,

  ///刷新 数据
  refreshLogout,

  ///切换导航
  exchangeNav,

  ///刷新规格弹窗
  refreshSkuPopup,

  ///刷新优惠弹窗
  refreshDiscountPopup,

  ///刷新微页面
  refreshMicroIndex,

  ///刷新订单列表
  refreshOrderList,

  ///刷新评论列表
  refreshCommentList,

  ///刷新抽奖
  refreshRaffle,
}
